package net.jjjshop.front.service.user.impl;

import lombok.extern.slf4j.Slf4j;
import net.jjjshop.common.entity.user.User;
import net.jjjshop.common.entity.user.UserBalanceLog;
import net.jjjshop.framework.common.exception.BusinessException;
import net.jjjshop.front.mapper.user.UserRechargeMapper;
import net.jjjshop.front.service.user.UserRechargeService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Objects;
import java.util.logging.Logger;

/**
 * UserRechargeServiceImpl
 *
 * @author 武子
 * @date 2025/3/3
 */
@Slf4j
@Service
public class UserRechargeServiceImpl implements UserRechargeService {

    @Autowired
    private UserRechargeMapper userRechargeMapper;

    @Override
    public Boolean updRecharge(User user) {
        try {
            user.setUpdateTime(new java.util.Date());
            // 调用 Mapper 层方法执行充值操作
            Boolean recharge = userRechargeMapper.updRecharge(user);

            // 如果充值成功，添加充值记录
            UserBalanceLog userBalanceLog = new UserBalanceLog();
            userBalanceLog.setUserId(user.getUserId());
            userBalanceLog.setScene(10);
            userBalanceLog.setMoney(user.getBalance());
            String remark = "用户充值";
            userBalanceLog.setDescription(remark);
            userBalanceLog.setRemark(remark);
            userBalanceLog.setAppId(10001);
            userBalanceLog.setCreateTime(new java.util.Date());
            Boolean addRechargeLog = userRechargeMapper.addRechargeLog(userBalanceLog);

            if(addRechargeLog){
                return recharge;
            }else {
                throw new BusinessException("用户充值失败");
            }
        } catch (Exception e) {
            // 发生异常时进行回滚，确保数据一致性
            throw new RuntimeException("用户充值失败", e);
        }
    }

    /**
     * 根据用户ID获取用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public User getById(Integer userId) {
        return userRechargeMapper.getById(userId);
    }
}
